import { _decorator, AnimationClip, Node, Animation, Button, Component, EventHandler, Sprite, SpriteFrame, sys, UITransform, view, Widget, tween, Vec3, UIOpacity, Mask, Label, math, Layout } from 'cc';
import { createUILabel, createUINode, destroyNode, getFrameAllAsset, getFrameAsset, getRandomNumber, setListTrantion, setRoleloadDir } from '../utils';
import DataManager from '../Runtime/DataManager';
import ResourceManager from '../Runtime/ResourceManager';
import { CHARGING_NAME_ENUM, ENEMY_NAME_ENUM, HELMET_NAME_ENUM, LEAPING_NAME_ENUM } from '../../Enums';
const { ccclass } = _decorator;
import { userStore } from "../service/user"
import { useSocket } from '../service/socket';
import dayjs from "../utils/dayjs.min.js"
const wx = window['wx']
@ccclass('HomeElement')
export class HomeElement extends Component {
    tokenList = [{
        label: "开 始 游 戏",
        handler: "playGame",
    }, {
        label: "联 机 模 式",
        handler: "onLineGame",
    }, {
        label: "加 入 房 间",
        handler: "showJoinContent",
    },
    // {
    //     label: "游 戏 帮 助",
    //     handler: "gameHelp",
    // }, 
    {
        label: "退 出 登 录",
        handler: "logout",
    }
    ]
    loginList = [
        {
            label: "登 录 游 戏",
            handler: "loginGame",
        }, {
            label: "登 录 游 戏1",
            handler: "loginGame1",
        }, {
            label: "试 玩 关 卡",
            handler: "trialLevels",
        },
    ]
    actionList = []
    enemy_list: Array<string> = ['dumb', 'charging', 'helmet', 'leaping']
    animation_list: Array<number> = [1, 2, 3, 6, 7, 8] //4, 5,
    role_list: Array<string> = ['blueLead', 'greenLead']
    prop_list: Array<number> = [1, 2, 3, 146, 160]
    play_eat: Boolean = false
    play_music: boolean
    can_animation: Boolean = true
    callBack
    close_node: Node
    easterEgg: Node
    countdown
    playGameNode: Node
    init(play_music) {
        this.setActionList()
        this.play_music = play_music
        this.setBackground()
        this.setLogo()
        this.audioMute()
        this.loadEnemyAssets()
        this.adCountdown()
    }
    setActionList() {
        // if (userStore().token == '') {
        //     this.actionList = this.loginList
        // } else {
        //     this.actionList = this.tokenList
        //     useSocket().connect()
        // }
        this.actionList = this.tokenList
        useSocket().connect()
        setTimeout(() => {
            this.setActionButton()
        }, 5)

    }
    // 设置背景图
    async setBackground() {
        const node = createUINode("背景图片")
        node.setParent(this.node)
        let designSize = view.getVisibleSize()
        const transform = node.getComponent(UITransform)
        transform.setContentSize(designSize.width, designSize.height)
        const sprite = node.addComponent(Sprite)
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        let spriteFrames = await ResourceManager.Instance.loadDir("/assets/", SpriteFrame)
        sprite.spriteFrame = spriteFrames.find(item => item.name == "home-bg")
    }
    // 设置Logo
    async setLogo() {
        const node = createUINode("游戏Logo")
        node.setParent(this.node)
        createUILabel({ parentNode: node, text: "神奇小妖精", fontSize: 120, lineHeight: 100, color: "#85BEF3" })
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = -270
    }
    // 广告倒计时
    adCountdown() {
        let info = userStore().info
        // if(!info) return
        const node = createUINode("down")
        node.setParent(this.node.parent)
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 48
        widget.isAlignRight = true
        widget.right = 460
        if (sys.isMobile && typeof (wx) !== "undefined") {
            widget.right = 460
        } else {
            widget.right = 260
        }
        const labelNode = createUINode("downLabel")
        labelNode.setParent(node)
        const labelWidget = labelNode.addComponent(Widget)
        labelWidget.isAlignTop = true
        labelWidget.top = 0
        if (info.adViewing == 0) {
            createUILabel({ parentNode: labelNode, text: "免广告时间: 00:00", fontSize: 32 })
            let adTime
            if(info.adTime==null){
                adTime=dayjs('2000-01-01 00:00:00')
            }else{
                adTime=dayjs(userStore().info.adTime)
            }
            // if (info.adTime) {
                let label = labelNode.getComponent(Label)
                this.countdown = setInterval(() => {
                    let nowtime = dayjs().valueOf() //获取系统时间。利用加号将Date转换为时间戳
                    let inputtime =adTime.add(1, 'hour').valueOf() //获取用户输入的截止时间，利用加号将Date转换为时间戳
                    var sumtime = (inputtime - nowtime) / 1000
                    let f = parseInt((sumtime / 60 % 60) + '')//分
                    let m = parseInt((sumtime % 60) + '')//秒
                    if (f <= 0 && m <= 0) {
                        // clearInterval(this.countdown)
                        label.string = '免广告时间: 00:00'
                    } else {
                        label.string = `免广告时间: ${f<10?'0'+f:f}:${m<10?'0'+m:m}`
                    }
                }, 1000)
            // }
        } else {
            createUILabel({ parentNode: labelNode, text: "无需观看广告", fontSize: 32 })
        }
    }
    // 底部彩蛋
    createEasterEgg(content) {
        const easterEgg = createUINode("EasterEgg")
        easterEgg.setParent(content)
        let width = content.width
        let node = createUINode("homeowner")
        node.setParent(content)
        easterEgg.addComponent(Mask)
        const transform = easterEgg.getComponent(UITransform)
        transform.setContentSize(width, 120)
        const widget = easterEgg.addComponent(Widget)
        widget.isAlignBottom = true
        widget.bottom = 0
        widget.isAlignRight = true
        widget.right = 0
        this.easterEgg = easterEgg
        this.playBottomAnimation(easterEgg, true)
    }
    // 创建左侧房主
    createHomeowner(content, res) {
        let { node, name_node, plan_Node } = this.createHomeContent({
            nickName: res.ownerNickname,
            content, name: 'homeowner',
            ready: res.ownerReady,
            assets: DataManager.Instance.blueLeadAssets,
            id: res.ownerId
        })

        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 0
        widget.isAlignLeft = true
        widget.left = 0

        const name_widget = name_node.addComponent(Widget)
        name_widget.isAlignBottom = true
        name_widget.bottom = -100

        const plan_widget = plan_Node.addComponent(Widget)
        plan_widget.isAlignBottom = true
        plan_widget.bottom = 30
        plan_widget.isAlignHorizontalCenter = true
    }

    // 创建右侧成员
    createHomemember(content, res) {
        let { node, name_node, plan_Node } = this.createHomeContent({
            nickName: res.memberNickname,
            content, name: 'homemember',
            ready: res.memberReady,
            assets: DataManager.Instance.greenLeadAssets,
            id: res.memberId
        })
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 0
        widget.isAlignRight = true
        widget.right = 0

        const name_widget = name_node.addComponent(Widget)
        name_widget.isAlignBottom = true
        name_widget.bottom = -100

        const plan_widget = plan_Node.addComponent(Widget)
        plan_widget.isAlignBottom = true
        plan_widget.bottom = 26
        plan_widget.isAlignHorizontalCenter = true
    }
    createHomeContent({ nickName, content, name, ready, assets, id }) {
        let width = content.width
        let height = content.height
        let node = createUINode(name)
        node.setParent(content)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(width / 2 - 10, height / 1.5 + 20)

        const user_node = createUINode("user_node")
        user_node.setParent(node)
        const user_widget = user_node.addComponent(Widget)
        user_widget.isAlignTop = true
        user_widget.top = 100
        const green_node = createUINode("green_node")
        green_node.setParent(user_node)
        green_node.setScale(1.4, 1.4)
        const sprite = green_node.addComponent(Sprite)
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        sprite.spriteFrame = getFrameAsset(assets, 'bottom/1.png').spriteFrame
        const name_node = createUINode("nickName")
        name_node.setParent(user_node)
        createUILabel({ parentNode: name_node, text: `${nickName}`, fontSize: 30 })

        const plan_Node = createUINode('plan_Node')
        plan_Node.setParent(node)
        if (userStore().info?.id == id) {
            const plan_button = plan_Node.addComponent(Button)
            const plan_handler = new EventHandler();
            plan_handler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
            plan_handler.component = 'homeManager';// 这个是脚本类名
            plan_handler.handler = 'updateRoom';
            plan_handler.customEventData = userStore().info?.id;
            plan_button.duration = .1
            plan_button.zoomScale = 0.95
            plan_button.transition = Button.Transition.SCALE
            plan_button.clickEvents.push(plan_handler)
        }
        createUILabel({ parentNode: plan_Node, text: `${ready == 0 ? '立即准备' : '取消准备'}`, color: `${ready == 0 ? DataManager.Instance.color : "#999"}` })

        return { node, name_node, plan_Node }
    }
    createDoubleSingle(topNode) {
        const singleNode = createUINode()
        singleNode.setParent(topNode)
        const singleWidget = singleNode.addComponent(Widget)
        singleWidget.isAlignTop = true
        singleWidget.top = 60
        singleWidget.isAlignLeft = true
        singleWidget.left = -15
        const transform = singleNode.getComponent(UITransform)
        transform.setContentSize(50, 50)
        const singleSprite = singleNode.addComponent(Sprite)
        singleSprite.sizeMode = Sprite.SizeMode.CUSTOM
        singleSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `502.png`).spriteFrame

        const singleNode1 = createUINode()
        singleNode1.setParent(topNode)
        const singleWidget1 = singleNode1.addComponent(Widget)
        singleWidget1.isAlignTop = true
        singleWidget1.top = 60
        singleWidget1.isAlignLeft = true
        singleWidget1.left = 35
        const transform1 = singleNode1.getComponent(UITransform)
        transform1.setContentSize(50, 50)
        const singleSprite1 = singleNode1.addComponent(Sprite)
        singleSprite1.sizeMode = Sprite.SizeMode.CUSTOM
        singleSprite1.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `504.png`).spriteFrame
    }
    createKeyboard(content) {
        let width = content.width
        let height = content.height
        const node = createUINode("")
        node.setParent(content)
        const value = createUINode("value")
        value.setParent(node)
        createUILabel({ parentNode: value, text: '******', fontSize: 50 })
        const widget = value.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 60
        const transform = node.getComponent(UITransform)
        transform.setContentSize(width, height)
        let keyboard = createUINode("keyboard")
        keyboard.setParent(node)
        let list = [[1, 2, 3, 0], [4, 5, 6, '删 除'], [7, 8, 9, '加 入']]
        let size = 110
        let key_width = 0
        let key_height = 0
        let spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `692.png`).spriteFrame
        list.forEach((item, index) => {
            key_width = 0
            key_height = 0
            item.forEach((item1, index1) => {
                const children = createUINode(`${item1}`)
                children.setParent(keyboard)
                const transform = children.getComponent(UITransform)
                if (typeof item1 == 'string') {
                    key_width = key_width + size * 1.5 + 10
                    transform.setContentSize(size * 1.5, size)
                } else {
                    key_width = key_width + size + 10
                    transform.setContentSize(size, size)
                }
                key_height = key_height + size
                const sprite = children.addComponent(Sprite)
                sprite.sizeMode = Sprite.SizeMode.CUSTOM
                sprite.spriteFrame = spriteFrame
                const widget = children.addComponent(Widget)
                widget.isAlignTop = true
                widget.top = -40 + (index * (size + 10))
                widget.isAlignLeft = true
                widget.left = -205 + (index1 * (size + 10))
                let labelNode = createUINode()
                labelNode.setParent(children)
                createUILabel({ parentNode: labelNode, text: item1 + '' })
                const button = children.addComponent(Button)
                const eventHandler = new EventHandler();
                eventHandler.target = this.node.parent;
                eventHandler.component = 'homeManager';
                eventHandler.handler = 'selectNumber';
                eventHandler.customEventData = item1 + '';
                button.duration = .1
                button.zoomScale = 0.95
                button.transition = Button.Transition.SCALE
                button.clickEvents.push(eventHandler)
            })
        })
    }
    createMemberEmpty(content) {
        let width = content.width
        let height = content.height
        let node = createUINode("memberEmpty")
        node.setParent(content)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(width / 2 - 10, height / 1.5 + 20)
        node.addComponent(Mask)
        const sprite1 = node.addComponent(Sprite)
        sprite1.sizeMode = Sprite.SizeMode.CUSTOM
        sprite1.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, 'default_sprite_splash.png').spriteFrame
        sprite1.color = new math.Color("#ffffff90")
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 0
        widget.isAlignRight = true
        widget.right = 0

        const close_node = createUINode("continue_node")
        close_node.setParent(node)
        const close_button = close_node.addComponent(Button)
        const close_handler = new EventHandler();
        close_handler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
        close_handler.component = 'homeManager';// 这个是脚本类名
        close_handler.handler = 'showJoinContent';
        close_button.duration = .1
        close_button.zoomScale = 0.95
        close_button.transition = Button.Transition.SCALE
        close_button.clickEvents.push(close_handler)
        createUILabel({ parentNode: close_node, text: "加入房间" })
        const close_widget = close_node.addComponent(Widget)
        close_widget.isAlignTop = true
        close_widget.top = 120


        const continue_node = createUINode("continue_node")
        continue_node.setParent(node)
        const continue_button = continue_node.addComponent(Button)
        const continue_handler = new EventHandler();
        continue_handler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
        continue_handler.component = 'homeManager';// 这个是脚本类名
        continue_handler.handler = 'inviteFriends';
        continue_button.duration = .1
        continue_button.zoomScale = 0.95
        continue_button.transition = Button.Transition.SCALE
        continue_button.clickEvents.push(continue_handler)
        createUILabel({ parentNode: continue_node, text: "邀请好友" })
        const continue_widget = continue_node.addComponent(Widget)
        continue_widget.isAlignBottom = true
        continue_widget.bottom = 130
    }
    // 创建底部按钮
    createBottomButton(maskBox, is_owner) {
        const close_node = createUINode("continue_node")
        close_node.setParent(maskBox)
        const close_button = close_node.addComponent(Button)
        const close_handler = new EventHandler();
        close_handler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
        close_handler.component = 'homeManager';// 这个是脚本类名
        close_handler.handler = 'changeAnimation';
        close_button.duration = .1
        close_button.zoomScale = 0.95
        close_button.transition = Button.Transition.SCALE
        close_button.clickEvents.push(close_handler)
        createUILabel({ parentNode: close_node, text: "关闭动画", fontSize: 30 })
        const close_widget = close_node.addComponent(Widget)
        close_widget.isAlignBottom = true
        close_widget.bottom = 30
        close_widget.isAlignRight = true
        close_widget.right = 60
        this.close_node = close_node
        // 房主按钮
        if (is_owner) {
            const continue_node = createUINode("continue_node")
            continue_node.setParent(maskBox)
            const continue_button = continue_node.addComponent(Button)
            const continue_handler = new EventHandler();
            continue_handler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
            continue_handler.component = 'homeManager';// 这个是脚本类名
            continue_handler.handler = 'nextStep';
            continue_button.duration = .1
            continue_button.zoomScale = 0.95
            continue_button.transition = Button.Transition.SCALE
            continue_button.clickEvents.push(continue_handler)
            createUILabel({ parentNode: continue_node, text: "下一步" })
            const continue_widget = continue_node.addComponent(Widget)
            continue_widget.isAlignBottom = true
            continue_widget.bottom = 30
            continue_widget.isAbsoluteVerticalCenter = true

            const disband_node = createUINode("disband_node")
            disband_node.setParent(maskBox)
            const disband_button = disband_node.addComponent(Button)
            const disband_handler = new EventHandler();
            disband_handler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
            disband_handler.component = 'homeManager';// 这个是脚本类名
            disband_handler.handler = 'dissolveRoom';
            disband_button.duration = .1
            disband_button.zoomScale = 0.95
            disband_button.transition = Button.Transition.SCALE
            disband_button.clickEvents.push(disband_handler)
            createUILabel({ parentNode: disband_node, text: "解散房间", fontSize: 30 })
            const disband_widget = disband_node.addComponent(Widget)
            disband_widget.isAlignBottom = true
            disband_widget.bottom = 30
            disband_widget.isAlignLeft = true
            disband_widget.left = 60
        } else {
            // 成员按钮
            const disband_node = createUINode("disband_node")
            disband_node.setParent(maskBox)
            const disband_button = disband_node.addComponent(Button)
            const disband_handler = new EventHandler();
            disband_handler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
            disband_handler.component = 'homeManager';// 这个是脚本类名
            disband_handler.handler = 'leaveRoom';
            disband_button.duration = .1
            disband_button.zoomScale = 0.95
            disband_button.transition = Button.Transition.SCALE
            disband_button.clickEvents.push(disband_handler)
            createUILabel({ parentNode: disband_node, text: "离开房间", fontSize: 30 })
            const disband_widget = disband_node.addComponent(Widget)
            disband_widget.isAlignBottom = true
            disband_widget.bottom = 30
            disband_widget.isAlignLeft = true
            disband_widget.left = 60
        }
    }
    // 静音/播放
    async audioMute() {
        const node = createUINode('audioMute')
        node.setParent(this.node.parent)
        node.setSiblingIndex(99)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(50, 50)
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 50
        widget.isAlignRight = true
        widget.right = 300
        if (sys.isMobile && typeof (wx) !== "undefined") {
            widget.right = 300
        } else {
            widget.right = 100
        }
        const sprite = node.addComponent(Sprite)
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        sprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '821.png').spriteFrame //spriteFrame.find(item => item.name == "821")
        const button = node.addComponent(Button)
        button.duration = .1
        button.zoomScale = 0.95
        button.transition = Button.Transition.SCALE
        const eventHandler = new EventHandler();
        eventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        eventHandler.component = 'HomeElement';// 这个是脚本类名
        eventHandler.handler = 'changeAudio';
        button.clickEvents.push(eventHandler)

        const closeNode = createUINode("closeNode")
        closeNode.setParent(node)
        closeNode.active = false
        const closeTransform = closeNode.getComponent(UITransform)
        closeTransform.setContentSize(35, 35)
        const closeSprite = closeNode.addComponent(Sprite)
        closeSprite.sizeMode = Sprite.SizeMode.CUSTOM
        closeSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '493.png').spriteFrame// spriteFrame.find(item => item.name == '493')
        closeNode.active = DataManager.Instance.mute
    }
    // 静音/播放事件
    changeAudio() {
        // if (DataManager.Instance.drawerNumber != 0) {
        //     return
        // }
        if (DataManager.Instance.mute) {
            if (this.play_music) {
                DataManager.Instance.audioMgr.resume()
            } else {
                DataManager.Instance.audioMgr.play(DataManager.Instance.audio.find(item => item.name == '1258_menu_music'))
                this.play_music = true
            }
        } else {
            DataManager.Instance.audioMgr.pause()
        }
        DataManager.Instance.mute = !DataManager.Instance.mute
        sys.localStorage.setItem('mute', JSON.stringify(DataManager.Instance.mute))
        this.changeCloseButton("audioMute")
    }
    changeCloseButton(name) {
        let node = this.node.parent.getChildByName(name)
        let closeNode = node.getChildByName("closeNode")
        closeNode.active = !closeNode.active
    }
    // 设置操作按钮
    setActionButton() {
        if (this.node.getChildByName('action-button')) {
            this.node.getChildByName('action-button').destroy()
        }
        const action = createUINode("action-button")
        action.setParent(this.node)
        this.actionList.forEach(async (item, index) => {
            const node = createUINode(item.label)
            node.setParent(action)
            const widget = node.addComponent(Widget)
            widget.isAlignTop = true
            widget.top = index * 100
            const transform = node.getComponent(UITransform)
            transform.setContentSize(250, 100)
            createUILabel({ parentNode: node, text: item.label, fontSize: 50, lineHeight: 50, color: "#D6D6D6" })
            const button = node.addComponent(Button)
            const eventHandler = new EventHandler();
            eventHandler.target = this.node.parent; // 这个 node 节点是你的事件处理代码组件所属的节点
            eventHandler.component = 'homeManager';// 这个是脚本类名
            eventHandler.handler = item.handler;
            button.clickEvents.push(eventHandler)
            button.duration = .1
            button.zoomScale = 0.95
            button.transition = Button.Transition.SCALE
        })
    }
    // 加载怪物的素材
    async loadEnemyAssets() {
        if (DataManager.Instance.dumbEnemyList.length == 0) {
            DataManager.Instance.dumbEnemyList = setRoleloadDir("dumb_enemy", ENEMY_NAME_ENUM)
        }
        if (DataManager.Instance.chargingEnemyList.length == 0) {
            DataManager.Instance.chargingEnemyList = setRoleloadDir("charging_enemy", CHARGING_NAME_ENUM)
        }
        if (DataManager.Instance.helmetEnemyList.length == 0) {
            DataManager.Instance.helmetEnemyList = setRoleloadDir("helmet_enemy", HELMET_NAME_ENUM)
        }
        if (DataManager.Instance.leapingEnemyList.length == 0) {
            DataManager.Instance.leapingEnemyList = setRoleloadDir("leaping_enemy", LEAPING_NAME_ENUM)
        }
    }
    clearCallBack() {
        clearTimeout(this.callBack)
        this.callBack = null
    }
    onDestroy() {
        this.clearCallBack()
        clearInterval(this.countdown)
    }
    // 播放底部动画
    playBottomAnimation(node, first = false) {
        if (!this.can_animation) return
        let random = getRandomNumber(0, this.animation_list.length - 1)
        let random_number = this.animation_list[random]
        this.animation_list.splice(random, 1)
        if (this.animation_list.length == 0) {
            this.animation_list = [1, 2, 3, 6, 7, 8] //4, 5,
        }
        this.clearCallBack()
        let time
        // if (first) {
        //     time = getRandomNumber(7000, 8000)
        // } else {
        time = getRandomNumber(10000, 20000)
        // }

        if (random_number == 1) {
            this.callBack = setTimeout(() => {
                this.playEnemyOrUser(node)
            }, time)
        } else if (random_number == 2) {
            this.callBack = setTimeout(() => {
                this.playEnemyOrProp(node)
            }, time)
        } else if (random_number == 3) {
            this.callBack = setTimeout(() => {
                this.playEnemyOrPropOrUser(node)
            }, time)
        } else if (random_number == 4) {
            // this.callBack = setTimeout(() => {
            //     this.playUserLaterEnemy(node)
            // }, time)
        } else if (random_number == 5) {
            // this.callBack = setTimeout(() => {
            //     this.playEnemyLaterUser(node)
            // }, time)
        } else if (random_number == 6) {
            this.callBack = setTimeout(() => {
                this.playUserDeath(node)
            }, time)
        } else if (random_number == 7) {
            this.callBack = setTimeout(() => {
                this.playUserEatEnemy(node)
            }, time)
        } else if (random_number == 8) {
            this.callBack = setTimeout(() => {
                this.streetPatrolAnimation(node)
            }, time)
        }
    }
    changeAnimation() {
        this.can_animation = !this.can_animation
    }
    // 怪物追蓝色小人的动画
    async playEnemyOrUser(node) {
        let direction_list = ['left', 'right']
        let direction = direction_list[getRandomNumber(0, direction_list.length - 1)]
        let enemy = this.enemy_list[getRandomNumber(0, this.enemy_list.length - 1)]
        let eat = getRandomNumber(0, 3) == 0
        this.play_eat = eat
        let role = this.role_list[getRandomNumber(0, this.role_list.length - 1)]
        await Promise.all([
            this.createEnemy({ node, direction, enemy, }),
            this.createUser({ node, direction, eat, role })
        ])
        this.playBottomAnimation(node)
    }
    // 怪物被道具追的动画
    async playEnemyOrProp(node) {
        let direction_list = ['left', 'right']
        let direction = direction_list[getRandomNumber(0, direction_list.length - 1)]
        let enemy = this.enemy_list[getRandomNumber(0, this.enemy_list.length - 1)]
        let text = this.prop_list[getRandomNumber(0, this.prop_list.length - 1)]
        await Promise.all([
            this.createEnemy({ node, direction, enemy, delayTime: 0 }),
            this.createProp({ node, direction, text, delayTime: 2, toTime: 6 })
        ])
        this.playBottomAnimation(node)
    }
    // 角色被怪物追被道具追
    async playEnemyOrPropOrUser(node) {
        let direction_list = ['left', 'right']
        let direction = direction_list[getRandomNumber(0, direction_list.length - 1)]
        let enemy = this.enemy_list[getRandomNumber(0, this.enemy_list.length - 1)]
        let eat = getRandomNumber(0, 3) == 0
        this.play_eat = eat
        let text = this.prop_list[getRandomNumber(0, this.prop_list.length - 1)]
        let role = this.role_list[getRandomNumber(0, this.role_list.length - 1)]
        await Promise.all([
            this.createEnemy({ node, direction, enemy, number: enemy == 'charging' ? 1 / 30 : 1 / 20, toTime: enemy == 'charging' ? getRandomNumber(32, 40) / 10 : getRandomNumber(45, 46) / 10 }),
            this.createUser({ node, direction, eat, number: 1 / 40, role }),
            this.createProp({ node, direction, text, delayTime: 3 })
        ])
        this.playBottomAnimation(node)
    }
    // 怪物回头道具停止动画
    async playEnemyLaterUser(node) {
        let direction_list = ['left', 'right']
        let direction = direction_list[getRandomNumber(0, direction_list.length - 1)]
        let enemy = this.enemy_list[getRandomNumber(0, this.enemy_list.length - 1)]
        let text = this.prop_list[getRandomNumber(0, this.prop_list.length - 1)]
        let prop_node = await this.createProp({ node, direction, text, play_animation: false })
        let { enemy_node, list } = await this.createEnemy({ node, direction, enemy, play_animation: false })
        let offsetX = -getRandomNumber(200, 400)
        if (direction == 'left') {
            offsetX = getRandomNumber(200, 400)
        }
        let { x } = prop_node.getPosition()
        prop_node.setPosition(x + offsetX * 3, 0)
        let { endX } = this.getWidthAndPosition(node, direction)
        let random = getRandomNumber(2, 10)
        let randomTime = getRandomNumber(1500, 3000)
        tween(enemy_node)
            .delay(0)
            .to(6, { position: new Vec3(endX / random, 0, 0) })
            .call(() => {
                let animation = enemy_node.getComponent(Animation)
                animation.pause()
                if (direction == 'left') {
                    enemy_node.setScale(1.5, 1.5)
                } else {
                    enemy_node.setScale(-1.5, 1.5, 1)
                }
                setTimeout(() => {
                    if (direction == 'left') {
                        enemy_node.setScale(-1.5, 1.5, 1)
                    } else {
                        enemy_node.setScale(1.5, 1.5)
                    }
                    animation.play()
                }, randomTime)
                tween(enemy_node)
                    .delay(randomTime / 1000)
                    .to(4, { position: new Vec3(endX - offsetX * 3, 0, 0) })
                    .call(() => {
                        destroyNode(enemy_node)
                    })
                    .start()
            })
            .start()
        tween(prop_node)
            .to(6, { position: new Vec3(endX / random + offsetX, 0, 0) })
            .call(() => {
                tween(prop_node)
                    .delay(randomTime / 1000)
                    .to(3, { position: new Vec3(endX - offsetX, 0, 0) })
                    .call(() => {
                        destroyNode(prop_node)
                        this.playBottomAnimation(node)
                    })
                    .start()
            })
            .start()
    }
    // 角色回头怪物停止动画
    async playUserLaterEnemy(node) {
        let direction_list = ['left', 'right']
        let direction = direction_list[getRandomNumber(0, direction_list.length - 1)]
        let enemy = this.enemy_list[getRandomNumber(0, this.enemy_list.length - 1)]
        let eat = getRandomNumber(0, 3) == 0
        this.play_eat = eat
        let { enemy_node } = await this.createEnemy({ node, direction, enemy, play_animation: false })
        let offsetX = -getRandomNumber(200, 400)
        if (direction == 'left') {
            offsetX = getRandomNumber(200, 400)
        }
        let { x } = enemy_node.getPosition()
        enemy_node.setPosition(x + offsetX, 0)
        let role = this.role_list[getRandomNumber(0, this.role_list.length - 1)]
        let { user_node, list } = await this.createUser({ node, direction, eat, play_animation: false, role })
        let { endX } = this.getWidthAndPosition(node, direction)
        let random = getRandomNumber(2, 10)
        let randomTime = getRandomNumber(1500, 3000)
        tween(user_node)
            .delay(0)
            .to(6, { position: new Vec3(endX / random, 0, 0) })
            .call(() => {
                let spriteFrame
                let sprite = user_node.getComponent(Sprite)
                let animation = user_node.getComponent(Animation)
                animation.pause()
                let text = ""
                if (direction == 'left') {
                    text = eat ? 'right_eat' : "right"
                } else {
                    text = eat ? 'left_eat' : "left"
                }
                spriteFrame = list.find(item => item.type == text).spriteList[0]
                sprite.spriteFrame = spriteFrame
                setTimeout(() => {
                    animation.play()
                }, randomTime)
                tween(user_node)
                    .delay(randomTime / 1000)
                    .to(6, { position: new Vec3(endX - offsetX, 0, 0) })
                    .call(() => {
                        destroyNode(user_node)
                    })
                    .start()
            })
            .start()
        tween(enemy_node)
            .to(6, { position: new Vec3(endX / random + offsetX, 0, 0) })
            .call(() => {
                let animation = enemy_node.getComponent(Animation)
                animation.pause()
                setTimeout(() => {
                    animation.play()
                }, randomTime)
                tween(enemy_node)
                    .delay(randomTime / 1000)
                    .to(6, { position: new Vec3(endX, 0, 0) })
                    .call(() => {
                        this.playBottomAnimation(node)
                        destroyNode(enemy_node)
                    })
                    .start()
            })
            .start()
    }
    // 怪物追到角色角色晕倒消失的动画
    async playUserDeath(node) {
        let direction_list = ['left', 'right']
        let direction = direction_list[getRandomNumber(0, direction_list.length - 1)]
        let enemy = this.enemy_list[getRandomNumber(0, this.enemy_list.length - 1)]
        let eat = getRandomNumber(0, 3) == 0
        this.play_eat = eat
        let { enemy_node } = await this.createEnemy({ node, direction, enemy, number: 1 / 30, play_animation: false })
        let offsetX = -getRandomNumber(200, 400)
        let toX = -20
        if (direction == 'left') {
            toX = 20
            offsetX = getRandomNumber(200, 400)
        }
        let { x } = enemy_node.getPosition()
        enemy_node.setPosition(x + offsetX + offsetX, 0)
        let role = this.role_list[getRandomNumber(0, this.role_list.length - 1)]
        let { user_node, list } = await this.createUser({ node, direction, eat, number: 1 / 30, play_animation: false, role })
        let { endX } = this.getWidthAndPosition(node, direction)
        let random = getRandomNumber(2, 10)
        let randomTime = getRandomNumber(4500, 6000)
        tween(user_node)
            .to(randomTime / 1000, { position: new Vec3(endX / random, 0, 0) })
            .call(() => {
                let { x } = user_node.getPosition()
                tween(user_node)
                    .to(.2, { position: new Vec3(x, 30, 0) })
                    .call(() => {
                        tween(user_node)
                            .to(.2, { position: new Vec3(x, 0, 0) })
                            .call(() => {
                                let spriteFrame
                                let sprite = user_node.getComponent(Sprite)
                                let animation = user_node.getComponent(Animation)
                                animation.defaultClip = setListTrantion(list.find(item => item.type == 'dizzy').spriteList, "user", AnimationClip.WrapMode.Default)
                                spriteFrame = list.find(item => item.type == 'dizzy').spriteList[0]
                                sprite.spriteFrame = spriteFrame
                                animation.play()
                                animation.on(
                                    Animation.EventType.FINISHED,
                                    this.onBrickFinished,
                                    this
                                );
                                setTimeout(() => {
                                    this.playBottomAnimation(node)
                                }, 500)
                            })
                            .start()
                    })
                    .start()
            })
            .start()
        tween(enemy_node)
            .delay(0)
            .to(randomTime / 1000, { position: new Vec3(endX / random + toX, 0, 0) })
            .call(() => {
                tween(enemy_node)
                    .to(3, { position: new Vec3(endX - offsetX, 0, 0) })
                    .call(() => {
                        destroyNode(enemy_node)
                    })
                    .start()
            })
            .start()
    }
    // 怪物被道具追到晕倒后角色跑来吃掉的动画
    async playUserEatEnemy(node) {
        let direction_list = ['left', 'right']
        let direction = direction_list[getRandomNumber(0, direction_list.length - 1)]
        let enemy = this.enemy_list[getRandomNumber(0, this.enemy_list.length - 1)]
        let text = this.prop_list[getRandomNumber(0, this.prop_list.length - 1)]
        this.play_eat = false
        let prop_node = await this.createProp({ node, direction, text, play_animation: false })
        let role = this.role_list[getRandomNumber(0, this.role_list.length - 1)]
        let { user_node, list: user_list } = await this.createUser({ role, node, direction, eat: false, number: 1 / 30, play_animation: false })
        let { enemy_node, list } = await this.createEnemy({ node, direction, enemy, number: 1 / 30, play_animation: false })
        let offsetX = -getRandomNumber(200, 400)
        let toX = -20
        let stop = -100
        if (direction == 'left') {
            toX = 20
            stop = 100
            offsetX = getRandomNumber(200, 400)
        }
        let { x } = prop_node.getPosition()
        prop_node.setPosition(x + offsetX * 8, 0)
        let { x: user_x } = user_node.getPosition()
        user_node.setPosition(user_x + offsetX * 5, 0)
        let { endX } = this.getWidthAndPosition(node, direction)
        let random = getRandomNumber(2, 10)
        let randomTime = getRandomNumber(4500, 6000)
        tween(enemy_node)
            .to(randomTime / 1000, { position: new Vec3(endX / random, 0, 0) })
            .call(() => {
                let { x } = enemy_node.getPosition()
                tween(enemy_node)
                    .to(.2, { position: new Vec3(x, 30, 0) })
                    .call(() => {
                        tween(enemy_node)
                            .to(.2, { position: new Vec3(x, 0, 0) })
                            .call(() => {
                                let spriteFrame
                                let sprite = enemy_node.getComponent(Sprite)
                                let animation = enemy_node.getComponent(Animation)
                                animation.defaultClip = setListTrantion(list.find(item => item.type == 'bottom_dizzy').spriteList, "user", AnimationClip.WrapMode.Loop)
                                spriteFrame = list.find(item => item.type == 'bottom_dizzy').spriteList[0]
                                sprite.spriteFrame = spriteFrame
                                animation.play()
                            })
                            .start()
                    })
                    .start()
            })
            .start()
        tween(prop_node)
            .to(randomTime / 1000, { position: new Vec3(endX / random + toX, 0, 0) })
            .call(() => {
                tween(prop_node)
                    .to(3, { position: new Vec3(endX - offsetX * 4, 0, 0) })
                    .call(() => {
                        destroyNode(prop_node)
                    })
                    .start()
            })
            .start()
        tween(user_node)
            .delay(3)
            .to(randomTime / 1000, { position: new Vec3(endX / random + stop, 0, 0) })
            .call(() => {
                // let { x } = enemy_node.getPosition()
                let transform = user_node.getComponent(UITransform)

                let spriteFrame
                let sprite = user_node.getComponent(Sprite)
                user_node.addComponent(UIOpacity)
                let animation = user_node.getComponent(Animation)
                animation.defaultClip = setListTrantion(user_list.find(item => item.type == `${direction}_process`).spriteList, "user", AnimationClip.WrapMode.Default)
                spriteFrame = user_list.find(item => item.type == `${direction}_process`).spriteList[0]
                sprite.spriteFrame = spriteFrame
                if (direction == 'left') {
                    transform.setAnchorPoint(0.8, 0.5)
                } else {
                    transform.setAnchorPoint(0.3, 0.5)
                }
                animation.play()
                setTimeout(() => {
                    destroyNode(enemy_node)
                }, 220)
                setTimeout(() => {
                    animation.defaultClip = setListTrantion(user_list.find(item => item.type == "win").spriteList, "user", AnimationClip.WrapMode.Loop)
                    animation.play()
                    setTimeout(() => {
                        tween(user_node.getComponent(UIOpacity))
                            .to(.2, { opacity: 0 })
                            .call(() => {
                                this.playBottomAnimation(node)
                                destroyNode(user_node)
                            })
                            .start()
                    }, 1500)
                }, 1000)
            })
            .start()
    }
    // 所有角色和怪物巡街的动画
    async streetPatrolAnimation(node) {
        let direction_list = ['left', 'right']
        let direction = direction_list[getRandomNumber(0, direction_list.length - 1)]
        let eat = getRandomNumber(0, 3) == 0
        await Promise.all([
            this.createUser({ node, direction, eat, role: this.role_list[0] }),
            this.createUser({ node, direction, eat, role: this.role_list[1], delayTime: 1, }),
            this.createEnemy({ node, direction, enemy: this.enemy_list[0], delayTime: 2 }),
            this.createEnemy({ node, direction, enemy: this.enemy_list[1], delayTime: 3, run: false }),
            this.createEnemy({ node, direction, enemy: this.enemy_list[2], delayTime: 4 }),
            this.createEnemy({ node, direction, enemy: this.enemy_list[3], delayTime: 5 }),
            this.createProp({ node, direction, text: this.prop_list[0], delayTime: 6, toTime: 6 }),
            this.createProp({ node, direction, text: this.prop_list[1], delayTime: 7, toTime: 6 }),
            this.createProp({ node, direction, text: this.prop_list[2], delayTime: 8, toTime: 6 }),
            this.createProp({ node, direction, text: this.prop_list[3], delayTime: 9, toTime: 6 }),
            this.createProp({ node, direction, text: this.prop_list[4], delayTime: 10, toTime: 6 })
        ])
        this.playBottomAnimation(node)
    }
    onBrickFinished(type: Animation.EventType, state) {
        destroyNode(state._targetNode)
    }
    // 怪物动画
    async createEnemy({ node, enemy, direction, delayTime = 2, toTime = 6, play_animation = true, number = 1 / 20, run = true }) {
        let { width, endX, targetX } = this.getWidthAndPosition(node, direction)
        let enemy_node = createUINode("enemy-tips")
        enemy_node.setParent(node)
        enemy_node.setPosition(targetX, -20)
        if (direction == 'left') {
            enemy_node.setScale(-1.5, 1.5, 1)
        } else {
            enemy_node.setScale(1.5, 1.5)
        }
        let sprite_text = enemy == 'charging' && run ? direction + '_run' : direction
        let list = this.getEnemyList(enemy)
        const sprite = enemy_node.addComponent(Sprite)
        sprite.spriteFrame = list.find(item => item.type == sprite_text).spriteList[0]
        const animation = enemy_node.addComponent(Animation)
        animation.defaultClip = setListTrantion(list.find(item => item.type == sprite_text).spriteList, "enemy", AnimationClip.WrapMode.Loop, number)
        animation.play()
        if (play_animation) {
            await this.playSimpleAnimation({ node: enemy_node, delayTime, toTime, endX })
        } else {
            return { enemy_node, list }
        }
    }
    // 角色动画
    async createUser({ node, direction, eat, number = 1 / 20, toTime = 6, play_animation = true, role, delayTime = 0 }) {
        let { width, endX, targetX } = this.getWidthAndPosition(node, direction)
        let sprite_text = eat ? direction + '_eat' : direction
        let user_node = createUINode("user-tips")
        user_node.setParent(node)
        user_node.setPosition(targetX, 0)
        user_node.setScale(1.5, 1.5)
        let list = this.setRoleloadDir(role)
        const sprite = user_node.addComponent(Sprite)
        sprite.spriteFrame = list.find(item => item.type == sprite_text).spriteList[0]
        const animation = user_node.addComponent(Animation)
        animation.defaultClip = setListTrantion(list.find(item => item.type == sprite_text).spriteList, "user", AnimationClip.WrapMode.Loop, number)
        animation.play()
        if (play_animation) {
            await this.playSimpleAnimation({ node: user_node, delayTime, toTime, endX })
        } else {
            return { user_node, list }
        }
    }
    // 道具动画
    async createProp({ node, direction, text, delayTime = 2.1, toTime = 4, play_animation = true }) {
        let { width, endX, targetX } = this.getWidthAndPosition(node, direction)
        let prop_node = createUINode("prop-tips")
        prop_node.setParent(node)
        prop_node.setScale(1.5, 1.5)
        prop_node.setPosition(targetX, -20)
        const sprite = prop_node.addComponent(Sprite)
        sprite.spriteFrame = getFrameAsset(DataManager.Instance.mapAssets, `${text}.png`).spriteFrame
        if (play_animation) {
            await this.playSimpleAnimation({ node: prop_node, delayTime, toTime, endX, audio: text == '160' ? DataManager.Instance.audio.find(item => item.name == '1237') : null })
        } else {
            return prop_node
        }
    }
    // 播放动画
    playSimpleAnimation({ node, delayTime, toTime, endX, destroy = true, audio = null }) {
        return new Promise<Boolean>((resolve, reject) => {
            tween(node)
                .delay(delayTime)
                .to(toTime, { position: new Vec3(endX, 0, 0) })
                .call(() => {
                    if (audio) {
                        DataManager.Instance.audioMgr.playOneShot(audio, 0.4)
                    }
                    if (destroy) {
                        destroyNode(node)
                    }
                    resolve(true)
                })
                .start()
        })
    }
    // 获取坐标
    getWidthAndPosition(node, direction) {
        let width = node.width
        let targetX = 0 - width / 2 - 50
        let endX = width / 2 + 50
        if (direction == 'left') {
            targetX = width / 2 + 50
            endX = 0 - width / 2 - 50
        }
        return {
            width, targetX, endX
        }
    }
    // 设置图片数组
    setRoleloadDir(role: string) {
        let typeList = ['right', 'left', 'left_eat', 'right_eat', "dizzy", "win", "left_process", "right_process", "bottom"]
        let arr = role == 'blueLead' ? DataManager.Instance.blueLeadAssets : DataManager.Instance.greenLeadAssets
        let list = []
        for (let i = 0; i < typeList.length; i++) {
            let item = typeList[i]
            let title = `${item}/`
            let spriteList = arr.jsonAsset.filter(item => item.filename.includes(`${title}`))
            list.push({
                type: item,
                name: role + '_' + item,
                spriteList: getFrameAllAsset(arr, spriteList),
                wrapMode: item.includes("process") || item.includes("dizzy") ? AnimationClip.WrapMode.Default : AnimationClip.WrapMode.Loop,
            })
        }
        return list
    }
    getEnemyList(enemy) {
        if (enemy == 'dumb') {
            return DataManager.Instance.dumbEnemyList
        } else if (enemy == 'charging') {
            return DataManager.Instance.chargingEnemyList
        } else if (enemy == 'helmet') {
            return DataManager.Instance.helmetEnemyList
        } else if (enemy == 'leaping') {
            return DataManager.Instance.leapingEnemyList
        }
    }
}


